// UI相关功能

// 更新配送员UI
function updateDeliveryPersonUI() {
    if (currentDeliveryPerson) {
        deliveryPersonName.textContent = currentDeliveryPerson.name;
        deliveryPersonStatus.textContent = formatDeliveryPersonStatus(currentDeliveryPerson.status);
        deliveryPersonStatus.className = `badge ${getStatusBadgeClass(currentDeliveryPerson.status)} ms-1`;
        statusIndicator.className = `status-indicator ${getStatusIndicatorClass(currentDeliveryPerson.status)}`;
    }
}

// 显示订单列表
function displayOrders(orders) {
    if (!orders || orders.length === 0) {
        noOrdersMessage.style.display = 'block';
        return;
    }

    const ordersHtml = orders.map(order => `
        <div class="card order-card">
            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <h5 class="mb-0">订单号: ${order.orderNumber}</h5>
                <span class="badge ${getOrderStatusBadgeClass(order.status)}">${formatOrderStatus(order.status)}</span>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <p class="mb-2"><i class="bi bi-box-seam me-2"></i><strong>物品:</strong> ${order.itemDescription || 'N/A'}</p>
                        <p class="mb-2"><i class="bi bi-rulers me-2"></i><strong>重量:</strong> ${order.weight ? order.weight + ' kg' : 'N/A'}</p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-2"><i class="bi bi-calendar-plus me-2"></i><strong>创建时间:</strong> ${formatDate(order.creationTime)}</p>
                        <p class="mb-2"><i class="bi bi-cash-coin me-2"></i><strong>费用:</strong> ${order.calculatedFee ? '¥' + order.calculatedFee.toFixed(2) : 'N/A'}</p>
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-md-6">
                        <h6 class="card-subtitle mb-1 text-muted"><i class="bi bi-person-up me-1"></i>发货方</h6>
                        <p class="card-text mb-1 small">${formatAddress(order.shipperInfo)}</p>
                    </div>
                    <div class="col-md-6">
                        <h6 class="card-subtitle mb-1 text-muted"><i class="bi bi-person-down me-1"></i>收货方</h6>
                        <p class="card-text mb-1 small">${formatAddress(order.recipientInfo)}</p>
                    </div>
                </div>
                <div class="text-end mt-3">
                    <button class="btn btn-sm btn-outline-primary view-order-btn" data-order-number="${order.orderNumber}">
                        <i class="bi bi-eye"></i> 查看详情
                    </button>
                </div>
            </div>
        </div>
    `).join('');

    ordersList.innerHTML = ordersHtml;

    // 添加查看详情按钮点击事件
    document.querySelectorAll('.view-order-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const orderNumber = this.getAttribute('data-order-number');
            viewOrderDetail(orderNumber);
        });
    });
}

// 显示订单详情
function displayOrderDetails(order) {
    const statusBadgeClass = getOrderStatusBadgeClass(order.status);
    const orderHtml = `
        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">订单号: ${order.orderNumber}</h5>
            <span class="badge ${statusBadgeClass}">${formatOrderStatus(order.status)}</span>
        </div>
        <ul class="list-group list-group-flush">
            <li class="list-group-item"><strong><i class="bi bi-card-text me-2"></i>物品描述:</strong> ${order.itemDescription || 'N/A'}</li>
            <li class="list-group-item"><strong><i class="bi bi-rulers me-2"></i>重量:</strong> ${order.weight !== null ? order.weight + ' kg' : 'N/A'}</li>
            <li class="list-group-item"><strong><i class="bi bi-cash-coin me-2"></i>计算费用:</strong> ${order.calculatedFee !== null ? '¥' + order.calculatedFee.toFixed(2) : 'N/A'}</li>
            <li class="list-group-item"><strong><i class="bi bi-calendar-plus me-2"></i>创建时间:</strong> ${order.creationTime ? formatDate(order.creationTime) : 'N/A'}</li>
            ${order.pickupTime ? `<li class="list-group-item"><strong><i class="bi bi-box-arrow-in-up me-2"></i>揽收时间:</strong> ${formatDate(order.pickupTime)}</li>` : ''}
            ${order.deliveryTime ? `<li class="list-group-item"><strong><i class="bi bi-calendar-check me-2"></i>送达时间:</strong> ${formatDate(order.deliveryTime)}</li>` : ''}
        </ul>
        <div class="card-body pt-2">
            <h6 class="card-subtitle mt-3 mb-1 text-muted"><i class="bi bi-person-up me-1"></i>发货方</h6>
            <p class="card-text mb-3 small">${formatAddress(order.shipperInfo)}</p>
            <h6 class="card-subtitle mb-1 text-muted"><i class="bi bi-person-down me-1"></i>收货方</h6>
            <p class="card-text mb-1 small">${formatAddress(order.recipientInfo)}</p>
        </div>
    `;

    orderDetailsCard.innerHTML = orderHtml;
}

// 显示物流轨迹
function displayLogisticsTraces(traces) {
    if (!traces || traces.length === 0) {
        logisticsTraces.innerHTML = '<p class="text-center">暂无物流轨迹</p>';
        return;
    }

    const tracesHtml = traces.map(trace => `
        <div class="trace-item">
            <div class="trace-time"><i class="bi bi-clock-history me-1"></i>${trace.timestamp ? formatDate(trace.timestamp) : '时间未知'}</div>
            <div class="trace-description">${trace.status ? formatOrderStatus(trace.status) : (trace.description || '状态未知')}</div>
            <div class="trace-details text-muted small">
                ${trace.location ? `<i class="bi bi-geo me-1"></i>地点: ${trace.location}` : ''}
                ${trace.operator ? `<span class="ms-2"><i class="bi bi-person-fill me-1"></i>操作员: ${trace.operator}</span>` : ''}
                ${(trace.status && trace.description && trace.description !== formatOrderStatus(trace.status)) ? `<span class="ms-2"><i class="bi bi-info-circle me-1"></i>备注: ${trace.description}</span>` : ''}
            </div>
        </div>
    `).join('');

    logisticsTraces.innerHTML = tracesHtml;
}

// 更新状态选择框
function updateStatusOptions(currentStatus) {
    // 清空选择框
    newStatusSelect.innerHTML = '';

    // 根据当前状态设置可选的下一状态
    const nextStatuses = getNextPossibleStatuses(currentStatus);
    nextStatuses.forEach(status => {
        const option = document.createElement('option');
        option.value = status;
        option.textContent = formatOrderStatus(status);
        newStatusSelect.appendChild(option);
    });

    // 如果没有可选状态，禁用表单
    if (nextStatuses.length === 0) {
        newStatusSelect.innerHTML = '<option value="">无可用状态更新</option>';
        updateStatusForm.querySelectorAll('input, textarea, select, button').forEach(el => el.disabled = true);
    } else {
        updateStatusForm.querySelectorAll('input, textarea, select, button').forEach(el => el.disabled = false);
    }
}

// 自动获取当前位置并填充表单
function fillCurrentLocation() {
    if (!navigator.geolocation) {
        console.warn('浏览器不支持地理位置功能');
        return;
    }

    navigator.geolocation.getCurrentPosition(
        async (position) => {
            try {
                const longitude = position.coords.longitude;
                const latitude = position.coords.latitude;
                
                // 使用经纬度获取地址描述（可以使用第三方API如高德地图或百度地图）
                // 这里简化处理，直接使用经纬度
                locationInput.value = `经度:${longitude.toFixed(6)}, 纬度:${latitude.toFixed(6)}`;
                
                // 如果有配送员当前位置，也可以直接使用
                if (currentDeliveryPerson && currentDeliveryPerson.currentLocation) {
                    locationInput.value = currentDeliveryPerson.currentLocation;
                }
            } catch (error) {
                console.error('获取位置信息失败:', error);
            }
        },
        (error) => {
            console.error('获取地理位置失败:', error);
        },
        {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0
        }
    );
}

// 显示个人信息
function showProfileView() {
    myOrdersView.style.display = 'none';
    orderDetailView.style.display = 'none';
    profileView.style.display = 'block';
    availableOrdersView.style.display = 'none';
    myOrdersLink.classList.remove('active');
    myProfileLink.classList.add('active');
    availableOrdersLink.classList.remove('active');

    // 显示个人信息
    if (currentDeliveryPerson) {
        const statusClass = getStatusBadgeClass(currentDeliveryPerson.status);
        const profileHtml = `
            <div class="mb-3">
                <h5 class="text-primary"><i class="bi bi-person-circle me-2"></i>${currentDeliveryPerson.name}</h5>
                <p class="text-muted mb-1"><i class="bi bi-telephone me-2"></i>${currentDeliveryPerson.phone || 'N/A'}</p>
                <p class="mb-3">
                    <span class="badge ${statusClass}">${formatDeliveryPersonStatus(currentDeliveryPerson.status)}</span>
                </p>
            </div>
            <hr>
            <div class="mb-3">
                <h6 class="text-muted">当前位置</h6>
                ${currentDeliveryPerson.currentLocation ? 
                    `<p><i class="bi bi-geo-alt me-1"></i>经度: ${currentDeliveryPerson.currentLocation[0].toFixed(6)}, 纬度: ${currentDeliveryPerson.currentLocation[1].toFixed(6)}</p>` : 
                    '<p class="text-muted">未设置位置</p>'}  
            </div>
            <hr>
            <div>
                <h6 class="text-muted">账号信息</h6>
                <p class="mb-1"><i class="bi bi-person-badge me-2"></i>配送员ID: ${currentDeliveryPerson.id || 'N/A'}</p>
            </div>
        `;
        profileInfo.innerHTML = profileHtml;
    } else {
        profileInfo.innerHTML = '<p class="text-center">加载个人信息中...</p>';
    }
    
    // 加载工作统计数据
    loadWorkStatistics();
}

// 显示我的订单视图
function showMyOrdersView() {
    myOrdersView.style.display = 'block';
    orderDetailView.style.display = 'none';
    profileView.style.display = 'none';
    availableOrdersView.style.display = 'none';
    myOrdersLink.classList.add('active');
    myProfileLink.classList.remove('active');
    availableOrdersLink.classList.remove('active');
}

// 显示订单详情视图
function showOrderDetailView() {
    myOrdersView.style.display = 'none';
    orderDetailView.style.display = 'block';
    profileView.style.display = 'none';
    availableOrdersView.style.display = 'none';
    
    // 添加这一行，使页面滚动到顶部
    window.scrollTo(0, 0);
}

// 显示可接单订单列表
function displayAvailableOrders(orders) {
    if (!orders || orders.length === 0) {
        noAvailableOrdersMessage.style.display = 'block';
        return;
    }

    const ordersHtml = orders.map(order => `
        <div class="card order-card">
            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <h5 class="mb-0">订单号: ${order.orderNumber}</h5>
                <span class="badge ${getOrderStatusBadgeClass(order.status)}">${formatOrderStatus(order.status)}</span>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <p class="mb-2"><i class="bi bi-box-seam me-2"></i><strong>物品:</strong> ${order.itemDescription || 'N/A'}</p>
                        <p class="mb-2"><i class="bi bi-rulers me-2"></i><strong>重量:</strong> ${order.weight ? order.weight + ' kg' : 'N/A'}</p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-2"><i class="bi bi-calendar-plus me-2"></i><strong>创建时间:</strong> ${formatDate(order.creationTime)}</p>
                        <p class="mb-2"><i class="bi bi-cash-coin me-2"></i><strong>费用:</strong> ${order.calculatedFee ? '¥' + order.calculatedFee.toFixed(2) : 'N/A'}</p>
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center">
                            <button class="btn btn-primary btn-sm" onclick="viewAvailableOrderDetails('${order.orderNumber}')">查看详情</button>
                            <button class="btn btn-success btn-sm" onclick="acceptOrder('${order.orderNumber}')">接单</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `).join('');

    availableOrdersList.innerHTML = ordersHtml;
}

// 显示可接单订单视图
function showAvailableOrdersView() {
    myOrdersView.style.display = 'none';
    orderDetailView.style.display = 'none';
    profileView.style.display = 'none';
    availableOrdersView.style.display = 'block';
    
    // 更新导航栏激活状态
    document.querySelectorAll('.nav-link').forEach(link => link.classList.remove('active'));
    availableOrdersLink.classList.add('active');
    
    // 刷新可接单订单列表
    loadAvailableOrders();
}

// 查看可接单订单详情
function viewAvailableOrderDetails(orderNumber) {
    // 可以复用现有的查看订单详情功能
    viewOrderDetail(orderNumber);
}

// 显示工作统计数据
function displayWorkStatistics(statistics, element) {
    // 计算进度条宽度
    const completionRate = statistics.completionRate || 0;
    const progressWidth = completionRate + '%';
    
    // 获取各状态订单数量
    const pendingCollection = statistics.ordersByStatus?.PENDING_COLLECTION || 0;
    const collected = statistics.ordersByStatus?.COLLECTED || 0;
    const transporting = statistics.ordersByStatus?.TRANSPORTING || 0;
    const outForDelivery = statistics.ordersByStatus?.OUT_FOR_DELIVERY || 0;
    const signed = statistics.ordersByStatus?.SIGNED || 0;
    const completed = statistics.ordersByStatus?.COMPLETED || 0;
    const failed = statistics.ordersByStatus?.DELIVERY_FAILED || 0;
    
    // 生成HTML
    const html = `
        <div class="row mb-3">
            <div class="col-md-6">
                <div class="d-flex align-items-center mb-2">
                    <i class="bi bi-box-seam me-2 text-primary"></i>
                    <span>总订单数:</span>
                    <span class="ms-auto fw-bold">${statistics.totalOrders || 0}</span>
                </div>
                <div class="d-flex align-items-center mb-2">
                    <i class="bi bi-check-circle me-2 text-success"></i>
                    <span>已完成订单:</span>
                    <span class="ms-auto fw-bold">${statistics.completedOrders || 0}</span>
                </div>
                <div class="d-flex align-items-center">
                    <i class="bi bi-percent me-2 text-info"></i>
                    <span>完成率:</span>
                    <span class="ms-auto fw-bold">${completionRate}%</span>
                </div>
            </div>
            <div class="col-md-6">
                <div class="d-flex align-items-center mb-2">
                    <i class="bi bi-calendar-day me-2 text-primary"></i>
                    <span>今日订单:</span>
                    <span class="ms-auto fw-bold">${statistics.todayOrders || 0}</span>
                </div>
                <div class="d-flex align-items-center">
                    <i class="bi bi-check-circle me-2 text-success"></i>
                    <span>今日完成:</span>
                    <span class="ms-auto fw-bold">${statistics.todayCompletedOrders || 0}</span>
                </div>
            </div>
        </div>
        
        <div class="mb-3">
            <label class="form-label small">完成率</label>
            <div class="progress" style="height: 10px;">
                <div class="progress-bar bg-success" role="progressbar" style="width: ${progressWidth}" 
                    aria-valuenow="${completionRate}" aria-valuemin="0" aria-valuemax="100">${completionRate}%</div>
            </div>
        </div>
        
        <div>
            <label class="form-label small">订单状态分布</label>
            <div class="row g-2 text-center">
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">待取件</div>
                        <div class="fw-bold">${pendingCollection}</div>
                    </div>
                </div>
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">已取件</div>
                        <div class="fw-bold">${collected}</div>
                    </div>
                </div>
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">运输中</div>
                        <div class="fw-bold">${transporting}</div>
                    </div>
                </div>
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">派送中</div>
                        <div class="fw-bold">${outForDelivery}</div>
                    </div>
                </div>
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">已签收</div>
                        <div class="fw-bold">${signed}</div>
                    </div>
                </div>
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">已完成</div>
                        <div class="fw-bold">${completed}</div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    element.innerHTML = html;
}

// 更新新订单列表UI
function updateNewOrdersUI() {
    if (newOrdersMap.size === 0) {
        newOrdersArea.style.display = 'none';
        newOrdersList.innerHTML = '<p class="text-center text-muted">正在等待新订单...</p>';
        return;
    }
    
    newOrdersArea.style.display = 'block';
    
    const ordersHtml = Array.from(newOrdersMap.values()).map(order => `
        <div class="card mb-2 new-order-card">
            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <h6 class="mb-0">订单号: ${order.orderNumber}</h6>
                <span class="badge bg-warning text-dark">待接单</span>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <p class="mb-1 small"><i class="bi bi-box-seam me-1"></i><strong>物品:</strong> ${order.itemDescription || 'N/A'}</p>
                        <p class="mb-1 small"><i class="bi bi-rulers me-1"></i><strong>重量:</strong> ${order.weight ? order.weight + ' kg' : 'N/A'}</p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-1 small"><i class="bi bi-calendar-plus me-1"></i><strong>创建时间:</strong> ${formatDate(order.creationTime)}</p>
                        <p class="mb-1 small"><i class="bi bi-cash-coin me-1"></i><strong>费用:</strong> ${order.calculatedFee ? '¥' + order.calculatedFee.toFixed(2) : 'N/A'}</p>
                    </div>
                </div>
                <div class="row mt-1">
                    <div class="col-md-6">
                        <p class="mb-1 small"><i class="bi bi-person-up me-1"></i><strong>发货方:</strong> ${formatAddress(order.shipperInfo)}</p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-1 small"><i class="bi bi-person-down me-1"></i><strong>收货方:</strong> ${formatAddress(order.recipientInfo)}</p>
                    </div>
                </div>
                <div class="text-end mt-2">
                    <button class="btn btn-sm btn-success accept-order-btn" data-order-number="${order.orderNumber}">
                        <i class="bi bi-check-circle"></i> 接单
                    </button>
                </div>
            </div>
        </div>
    `).join('');
    
    newOrdersList.innerHTML = ordersHtml;
    
    // 添加接单按钮点击事件
    document.querySelectorAll('.accept-order-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const orderNumber = this.getAttribute('data-order-number');
            acceptOrder(orderNumber);
        });
    });
}

// 辅助函数：显示提示信息
function showAlert(message, type = 'info') {
    alertArea.innerHTML = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    alertArea.style.display = 'block';

    // 5秒后自动关闭
    setTimeout(() => {
        const alert = alertArea.querySelector('.alert');
        if (alert) {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        }
    }, 5000);
}

// 辅助函数：显示/隐藏加载指示器
function showLoader(show) {
    mainLoader.style.display = show ? 'flex' : 'none';
}